﻿
#include "SerialLink.h"
#include <QApplication>

SerialLink::SerialLink(const QString & port_name,
                       int baud_,int data_bits ,
                       int stop_bits ,int parity_,QObject *parent)
     : LinkInterface{parent,Serial}
{
    baud(baud_);
    dataBits(data_bits);
    stopBits(stop_bits);
    parity(parity_);
    portName(port_name);
}

SerialLink::~SerialLink()
{
   disconnect();
}

bool SerialLink::connect()
{
   if (port_) {
       port_->close();
       for (unsigned i = 0; i < 10; i++) {
           QThread::usleep(1000);
           qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
       }
       port_->deleteLater();
       port_ = nullptr;
   }
   port_ = new QSerialPort(_portName, this);
   QObject::connect(port_, &QIODevice::readyRead, this, &SerialLink::readBytes_);

   port_->open(QIODevice::ReadWrite);
   if (!port_->isOpen() ) {
       port_->close();
       port_->deleteLater();
       port_ = nullptr;
       return false;
   }
   port_->setBaudRate     (_baud);
   port_->setDataBits     (static_cast<QSerialPort::DataBits>     (_dataBits));
   port_->setStopBits     (static_cast<QSerialPort::StopBits>     (_stopBits));
   port_->setParity       (static_cast<QSerialPort::Parity>       (_parity));
   isConnected_ = true;
   emit connectedChanged(isConnected_);
   return true;
}

bool SerialLink::isConnected(){
   return isConnected_;
}

void SerialLink::disConnect(void)
{
   isConnected_ = false;
   if (port_) {
       QObject::disconnect(port_, &QIODevice::readyRead, this, &SerialLink::readBytes_);
       port_->close();
       port_->deleteLater();
       port_ = nullptr;
   }
   emit connectedChanged(isConnected_);;
}

void SerialLink::readBytes_()
{
   if (port_ && port_->isOpen()) {
       qint64 byteCount = port_->bytesAvailable();
       if (byteCount) {
           auto bytes = port_->readAll();
           emit bytesReceived(this,bytes);
       }
   }
}

void SerialLink::writeBytes(QByteArray  data)
{
   if(port_ && port_->isOpen()) {
       emit bytesSent(this, data);
       port_->write(data);
   }
}





